<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Report extends CI_Controller {
	public function index(){
		#$this->session->userdata('user_id').'|'.$this->session->userdata('user_name');
		$this->layout->setLayout('default');
		$this->layout->setTitle('Administrator | Report');
		if(isset($_GET['code'])){
			$code = quotes_to_entities($_GET['code']);
			$filter = " AND sms_code='$code'";
		}
		$month = isset($_GET['month']) ? quotes_to_entities($_GET['month']) : date('Y-m');
		$year = isset($_GET['year']) ? $_GET['year'] : date('Y');
		if ($year == "") $year = date('Y');
		$month = isset($_GET['month']) ? $year . '-'.str_pad(quotes_to_entities($_GET['month']), 2, "0", STR_PAD_LEFT) : date('Y-m');
		
		$filter .= " AND receive_date BETWEEN '" . $month."-01 00:00:00" . "' AND '" . $month."-31 23:59:59" . "'";
		$arrDate = explode("-", $month);
		$data['month'] = $arrDate[1].'-'.$arrDate[0];
		// get earning data
		$sqlThisMonthEarning = "SELECT sms_ftp AS subtotal, 
								   DATE_FORMAT(receive_date, '%d-%m-%Y') AS earn_date
								FROM tdx_sms_stat WHERE 1=1 $filter";
		$monthQuery = $this->db->query($sqlThisMonthEarning);
		if ($monthQuery->num_rows() > 0){
			$arrData = array();
			$total = 0;
			foreach ($monthQuery->result_array() as $row){
				$arrData[$row['earn_date']] += intval($row['subtotal']);
				$total += intval($row['subtotal']);
			}
		}
		if(isset($_GET['date'])){
			$today = $_GET['date'];
			$sqlToday = "SELECT SUM(sms_ftp) AS subtotal
								FROM tdx_sms_stat WHERE receive_date BETWEEN '" . $today." 00:00:00" . "' AND '" . $today." 23:59:59" . "' $filter";
			$todayQuery = $this->db->query($sqlToday);
			$todayData = $todayQuery->row();
			$strDate = 'Ngày '.$_GET['date'];
			$data['earn_today'] = intval($todayData->subtotal);
		}
		else{
			$strDate = 'Hôm nay ('.date('d-m-Y').')';
			$data['earn_today'] = intval($arrData[date('d-m-Y')]);
		}
		$data['earn_yesterday'] = intval($arrData[date('d-m-Y', strtotime('-1 day'))]);
		$data['earn_this_month'] = $total;
		$data['str_date'] = $strDate;
		$data['month_data'] = $arrData;
		$data['currentUser'] = $this->session->userdata('user_name');
		$this->layout->view(THEME_DIR.'/reportall_index', $data);
	}
}